<?php
/**
 * 888888ba                 dP  .88888.                    dP                
 * 88    `8b                88 d8'   `88                   88                
 * 88aaaa8P' .d8888b. .d888b88 88        .d8888b. .d8888b. 88  .dP  .d8888b. 
 * 88   `8b. 88ooood8 88'  `88 88   YP88 88ooood8 88'  `"" 88888"   88'  `88 
 * 88     88 88.  ... 88.  .88 Y8.   .88 88.  ... 88.  ... 88  `8b. 88.  .88 
 * dP     dP `88888P' `88888P8  `88888'  `88888P' `88888P' dP   `YP `88888P' 
 *
 *                          m a g n a l i s t e r
 *                                      boost your Online-Shop
 *
 * -----------------------------------------------------------------------------
 * $Id: get_ebay_orders.php 889 2011-04-03 23:46:11Z MaW $
 *
 * (c) 2010 RedGecko GmbH -- http://www.redgecko.de
 *     Released under the GNU General Public License v2 or later
 * -----------------------------------------------------------------------------
 */

/*
NOCH TODO bei zusammengefassten Bestellungen:

Shipping konfigurierbar (vorerst wirds vom 1ten Artikel genommen)
promotion mail verbessern (im ersten Wurf wie bisher)

*/

defined('_VALID_XTC') or die('Direct Access to this location is not allowed.');

/* Hilfsfunktion: Attributwerte anhand von variation_products_model ermitteln */
# SKU unter dem Namen products_id uebermitteln, variation_products_model unter products_model
function variation_products_model2pOpt($variation_products_model, $products_id) {
	if (empty($variation_products_model)) return false;
	if (empty($products_id)) return false;
	$attrValues = array();
	$variation_attributes_select = 'SELECT variation_attributes
	    FROM '.TABLE_MAGNA_VARIATIONS;
	if ('artNr' == getDBConfigValue('general.keytype', '0')) $variation_attributes_select .= 
	    ' WHERE REPLACE(variation_products_model,\'ML\',\'\') = \''.ltrim($variation_products_model,'ML').'\'';
	else $variation_attributes_select .=
	    ' WHERE variation_products_model = \''.$variation_products_model.'\'';
	$variation_attributes_select .=
	    ' AND products_id = '.$products_id.'
	    ORDER BY variation_id DESC LIMIT 1';
	$variation_attributes = MagnaDB::gi()->fetchOne($variation_attributes_select);
	if (!$variation_attributes) return false;

	$options =''; $values = '';
	$attributes = explode('|', $variation_attributes);
	foreach ($attributes as $k => $attribute) {
		if (empty($attribute)) continue;
		list($attrValues[$k]['options_id'],$attrValues[$k]['options_values_id']) = explode(',',$attribute);
		$options .= $attrValues[$k]['options_id'].', ';
		$values .= $attrValues[$k]['options_values_id'].', ';
	}
	$lauguageID = MagnaDB::gi()->fetchOne('
		SELECT languages_id FROM '.TABLE_LANGUAGES.' l, '.TABLE_CONFIGURATION.' c
		WHERE c.configuration_key = \'DEFAULT_LANGUAGE\'
		AND c.configuration_value = l.code');
	$options = trim($options,', ');
	$values = trim($values,', ');
	$options_name_select = 'SELECT products_options_id, products_options_name
		FROM '.TABLE_PRODUCTS_OPTIONS.' WHERE language_id = '.$lauguageID.'
		AND products_options_id in ('.$options.')';
	$options_names_array = MagnaDB::gi()->fetchArray($options_name_select);
	$options_names = array();
	foreach ($options_names_array as $name) {
		$options_names[$name['products_options_id']] = $name['products_options_name'];
	}
	$options_values_name_select = 'SELECT products_options_values_id, products_options_values_name
		FROM '.TABLE_PRODUCTS_OPTIONS_VALUES.' WHERE language_id = '.$lauguageID.'
		AND products_options_values_id in ('.$values.')';
	$options_values_names_array = MagnaDB::gi()->fetchArray($options_values_name_select);
	foreach ($options_values_names_array as $name) {
		$options_values_names[$name['products_options_values_id']] = $name['products_options_values_name'];
	}
	$options_values_prices = array();
	$options_values_price_select = 'SELECT options_values_id, options_values_price
		FROM '.TABLE_PRODUCTS_ATTRIBUTES
		.' WHERE products_id = '.$products_id.'
		 AND options_id IN ('.$options.') AND options_values_id IN  ('.$values.')';
	$options_values_price_array = MagnaDB::gi()->fetchArray($options_values_price_select);
	foreach ($options_values_price_array as $price_row) {
		$options_values_prices[$price_row['options_values_id']] = $price_row['options_values_price'];
	}
	foreach ($attrValues as &$attr) {
		$attr['options_name'] = $options_names[$attr['options_id']];
		$attr['options_values_name'] = $options_values_names[$attr['options_values_id']];
		$attr['options_values_price'] = $options_values_prices[$attr['options_values_id']];
	}
	return $attrValues;
}

/* eBay Bestellungen importieren */ 
function magnaImportEbayOrders($mpID) {
	global $magnaConfig, $_magnaLanguage, $_modules;


	$mp = 'ebay';

	require_once(DIR_MAGNALISTER_MODULES.'ebay/ebayFunctions.php');
	require_once(DIR_MAGNALISTER_INCLUDES.'lib/classes/SimplePrice.php');

	/*
	require_once(DIR_MAGNALISTER_INCLUDES . 'lib/MagnaTestDB.php');
	$MagnaDB = MagnaTestDB::gi();
	/*/
	$MagnaDB = MagnaDB::gi();
	//*/
	
	$character_set_client = MagnaDB::gi()->mysqlVariableValue('character_set_client');
	
	$verbose = (MAGNA_CALLBACK_MODE == 'STANDALONE') && (get_class($MagnaDB) == 'MagnaTestDB');

	$simplePrice = new SimplePrice();
	
	$ShopInfo = array(
		'CustomerGroup' => getDBConfigValue($mp.'.CustomerGroup', $mpID),
		'OrderStatusOpen' => getDBConfigValue($mp.'.orderstatus.open', $mpID),
		'OrderStatusClosed' => getDBConfigValue($mp.'.orderstatus.closed', $mpID, 99)
	);
	$updateExchangeRate = getDBConfigValue(array($mp.'.exchangerate', 'update'), $mpID, false);

	# default shipping method
	if ('__ml_lump' == ($ShopInfo['DefaultShippingMethod'] = getDBConfigValue($mp.'.order.shippingmethod', $mpID, '__ml_lump'))) {
		$ShopInfo['DefaultShippingMethod'] = $ShopInfo['DefaultShippingMethodName']
		= getDBConfigValue($mp.'.order.shippingmethod.name', $mpID, 'ebay');
	} else {
		if (!class_exists('Shipping')) {
			require_once (DIR_MAGNALISTER_INCLUDES.'lib/classes/Shipping.php');
		}
		$shippingClass = new Shipping();
		$shippingMethods = $shippingClass->getShippingMethods();
		if (!empty($shippingMethods)) {
			foreach ($shippingMethods as $method) {
				if ($method['code'] == $ShopInfo['DefaultShippingMethod']) {
					$ShopInfo['DefaultShippingMethodName'] = $method['title'];
				}
			}
		}
	}

	# Display prices with tax included (true) or add the tax at the end (false)
	if ('oscommerce' == SHOPSYSTEM) {
		$displayPriceWithTax = (MagnaDB::gi()->fetchOne('SELECT configuration_value
				FROM '.TABLE_CONFIGURATION.
				' WHERE configuration_key = \'DISPLAY_PRICE_WITH_TAX\'') == 'true')?
			 true:false;
	} else {
	# customers_status_show_price_tax = 0 Preise netto anzeigen
	# customers_status_add_tax_ot = 1 MwSt am Ende draufaddieren
		#if(1 == (int)(MagnaDB::gi()->fetchOne('SELECT customers_status_add_tax_ot
		#		FROM '.TABLE_CUSTOMERS_STATUS.
		#		' WHERE customers_status_id = '.$ShopInfo['CustomerGroup']. ' LIMIT 1')))
		if((int)(MagnaDB::gi()->fetchOne('SELECT count(*) FROM '.TABLE_CUSTOMERS_STATUS.
					' WHERE customers_status_id = '.$ShopInfo['CustomerGroup'].
					' AND customers_status_show_price_tax = 0
					  AND customers_status_add_tax_ot = 1')) > 0)
			$displayPriceWithTax = false;
		else
			$displayPriceWithTax = true;
	}
	
	$lastImport = getDBConfigValue($mp.'.orderimport.lastrun', $mpID, 0);
	if (preg_match('
			/^([1-2][0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s'.
			'([0-1][0-9]|2[0-4]):([0-5][0-9]):([0-5][0-9])$/',
			$lastImport
	)) {
		# Since we only request non acknowledged orders, we go back in time by 7 days.
		$lastImport = strtotime($lastImport.' +0000') - 60 * 60 * 24 * 7;
	} else {
		$lastImport = 0;
	}

	$begin = strtotime(getDBConfigValue($mp.'.preimport.start', $mpID, '2011-05-01'));
	if ($begin > time()) {
		if ($verbose) echo "Date in the future --> no import\n";
		return;
	}
	if ($begin < MAGNA_ORDERS_DATERANGE_BEGIN) {
		if ($verbose) echo "Date in the past --> fix date\n";
		$begin = MAGNA_ORDERS_DATERANGE_BEGIN;
	}

	if ( ($lastImport > 0) && ($begin < $lastImport) ) {
		$begin = $lastImport;
	}
	#$begin -= 60 * 60 * 24 * 30 * 12;

	# Bestelldaten abfragen.
	$break = false;
	$offset = array (
		'COUNT' => 200,
		'START' => 0,
	);
	
	$processedOrders = array();

	$lastOrder = '';
	$allCurrencies = array();
	
	while (!$break) {
		@set_time_limit(60);
		$request = array(
			'ACTION' => 'GetOrdersForDateRange',
			'SUBSYSTEM' => 'eBay',
			'MARKETPLACEID' => $mpID,
			'BEGIN' => gmdate('Y-m-d H:i:s', $begin),
			'OFFSET' => $offset,
		);
		if ($verbose) echo print_m($request, '$request');
		try {
			$res = MagnaConnector::gi()->submitRequest($request);
		} catch (MagnaException $e) {
			$res = array();
			if (MAGNA_CALLBACK_MODE == 'STANDALONE') {
				echo print_m($e->getErrorArray(), 'Error: '.$e->getMessage(), true);
			}
			if (MAGNA_DEBUG && ($e->getMessage() == ML_INTERNAL_API_TIMEOUT)) {
				$e->setCriticalStatus(false);
			}
			$break = true;
		}
		if (!array_key_exists('DATA', $res) || empty($res['DATA'])) {
			if ($verbose) echo "No Data.\n";
			return false;
		}
		
		$break = !$res['HASNEXT'];
		$offset['START'] += $offset['COUNT'];

		$orders = $res['DATA'];
		#unset($res['DATA']);
		if ($verbose) echo print_m($res, '$res');
	
		# ggf. Zeichensatz korrigieren
		if ('utf8' != $character_set_client) {
			arrayEntitiesToLatin1($orders);
		}
	
		$syncBatch = array();
		
		# Bestelldaten durchgehen.
		foreach ($orders as $order) {
			/* {Hook} "GeteBayOrders_PreOrderImport": Is called before the eBay order in <code>$order</code> is imported.
				Variables that can be used:
				<ul><li>$order: The order that is going to be imported. The order is an 
				        associative array representing the structures of the order and customer related shop tables.</li>
				    <li>$mpID: The ID of the marketplace.</li>
				    <li>$MagnaDB: Instance of the magnalister database class. USE THIS for accessing the database during the
				        order import. DO NOT USE the shop functions for database access or MagnaDB::gi()!</li>
				</ul>
			*/
			if (($hp = magnaContribVerify('GeteBayOrders_PreOrderImport', 1)) !== false) {
				require($hp);
			}
			# eBay-OrderID == ItemID-TransactionID
			if ($verbose) echo "\n== Processing ".$order['orderInfo']['eBayOrderID'].". ==\n";
			if (!array_key_exists($order['order']['currency'], $allCurrencies)) {
				# Gibts die Waehrung auch im Shop?
				if (!$simplePrice->currencyExists($order['order']['currency'])) {
					if ($verbose) echo $order['order']['currency'] . ": Currency does not exist.\n";
					continue;
				}
				
				$simplePrice->setCurrency($order['order']['currency']);
				if ($updateExchangeRate) {
					$simplePrice->updateCurrencyByService();
				}
				$currencyValue = $simplePrice->getCurrencyValue();
				if ((float)$currencyValue <= 0.0) {
					if ($verbose) echo "CurrencyValue <= 0.\n";
					continue;
				}
				$allCurrencies[$order['order']['currency']] = $currencyValue;
			}
	
			$countryISO = $order['order']['billing_country_iso_code_2'];
	
			$simplePrice->setCurrency($order['order']['currency']);
			$order['order']['currency_value'] = $allCurrencies[$order['order']['currency']];
	
			if (MagnaDB::gi()->columnExistsInTable('customers_cid',TABLE_CUSTOMERS)) {
				$tmp_customer_id = MagnaDB::gi()->fetchRow('
					SELECT customers_id, customers_cid FROM '.TABLE_CUSTOMERS.' 
				 	WHERE customers_email_address=\''.$order['customer']['customers_email_address'].'\' 
				 	LIMIT 1
				');
				if (!$tmp_customer_id)
					$customersId = false;
				else {
					$customersId = $tmp_customer_id['customers_id'];
					$customersCId = $tmp_customer_id['customers_cid'];
				}
			} else {
				$customersId = MagnaDB::gi()->fetchOne('
					SELECT customers_id FROM '.TABLE_CUSTOMERS.'
					WHERE customers_email_address=\''.$order['customer']['customers_email_address'].'\' LIMIT 1
				');
			}
			
			$countryISO = $order['order']['billing_country_iso_code_2'];
	
			$billingCountry  = magnaGetCountryFromISOCode($order['order']['billing_country_iso_code_2']);
			$shippingCountry = magnaGetCountryFromISOCode($order['order']['delivery_country_iso_code_2']);
	
			# Muss ein neuer Kunde angelegt werden?
			if ($customersId === false) {
				# Der Kunde muss angelegt werden.
				$customers_password = randomString(10);
				$order['customer']['customers_password'] = md5($customers_password);
				
				if (SHOPSYSTEM != 'oscommerce') {
					$order['customer']['customers_status'] = $ShopInfo['CustomerGroup'];
					$order['customer']['account_type'] = '0';
				}
				$MagnaDB->insert(TABLE_CUSTOMERS, $order['customer']);
				
				# Kunden-ID herausfinden
				$customersId = $MagnaDB->getLastInsertID();
				# customers_cid bestimmen
				if (MagnaDB::gi()->columnExistsInTable('customers_cid',TABLE_CUSTOMERS)) {
					switch (getDBConfigValue('customers_cid.assignment', '0', 'none')) {
						case 'sequential': 
							$customersCId = MagnaDB::gi()->fetchOne('
					  		SELECT MAX(CAST(IFNULL(customers_cid,0) AS SIGNED))+1
					  		FROM '.TABLE_CUSTOMERS);
							break;
						case 'customers_id':
							$customersCId = $customersId;
							break;
						case 'none':
						default:
							if (isset($customersCId)) unset($customersCId);
							break;
					}
					if (isset($customersCId)) 
						MagnaDB::gi()->update(TABLE_CUSTOMERS, array('customers_cid' => $customersCId), array('customers_id' => $customersId));
				}
				
				# Infodatensatz erzeugen
				$MagnaDB->insert(TABLE_CUSTOMERS_INFO, array(
					'customers_info_id' => $customersId,
					'customers_info_date_account_created' => gmdate('Y-m-d H:i:s')
				));
				// echo 'DELETE FROM '.TABLE_CUSTOMERS_INFO.' WHERE customers_info_id=\''.$customersId.'\';'."\n\n";
	
				# Adressbuchdatensatz ergaenzen.
				$country = magnaGetCountryFromISOCode($order['order']['billing_country_iso_code_2']);
				$order['adress']['customers_id'] = $customersId;
				$order['adress']['entry_country_id'] = $billingCountry['countries_id'];
	
				$MagnaDB->insert(TABLE_ADDRESS_BOOK, $order['adress']);
	
				# Adressbuchdatensatz-Id herausfinden.
				$abId = $MagnaDB->getLastInsertID();
				// echo 'DELETE FROM '.TABLE_ADDRESS_BOOK.' WHERE customers_id=\''.$customersId.'\';'."\n\n";
	
				# Kundendatensatz updaten.
				$MagnaDB->update(TABLE_CUSTOMERS, array(
					'customers_default_address_id' => $abId
				), array (
					'customers_id' => $customersId
				));
			} else {
			# Falls Altkunde, haben wir kein Password, brauchen geeigneten Platzhalter
				switch($countryISO) {
					case('AT'):
					case('DE'): $customers_password = '(wie bekannt)';
						break;
					default:    $customers_password = '(as known)';
						break;
				}
			}
	
			if (0 <> MagnaDB::gi()->fetchOne('SELECT COUNT(*) FROM '.TABLE_MAGNA_ORDERS.'
				WHERE mpID = '.$mpID.' AND special like \'%'.$order['orderInfo']['eBayOrderID'].'%\''
			 )) {
				# Bestellung mit dieser ItemID / TransactionID existiert bereits.
				if ($verbose) echo "Order already exists.\n";
				$ordersId = MagnaDB::gi()->fetchOne('SELECT orders_id FROM '
				.TABLE_MAGNA_ORDERS.' WHERE mpID = '.$mpID
				.' AND special like \'%'.$order['orderInfo']['eBayOrderID'].'%\''
				.' ORDER BY orders_id DESC LIMIT 1');
				$processedOrders[] = array ('eBayOrderID' => $order['orderInfo']['eBayOrderID'],
							'shopsOrderID' => $ordersId );
				continue;
			}
	
			# Bestellung anlegen.
			# Hauptdatensatz in Tabelle "orders".

			$order['order']['customers_id'] = $customersId;
			$order['order']['customers_cid'] = $customersCId;
			$order['order']['customers_address_format_id'] = $order['order']['billing_address_format_id'] = magnaGetAddressFormatID($billingCountry['countries_id']);
			$order['order']['delivery_address_format_id']  = magnaGetAddressFormatID($shippingCountry['countries_id']);
			$order['order']['orders_status'] = $ShopInfo['OrderStatusOpen'];
	
			$order['order']['customers_country'] = $billingCountry['countries_name'];
			$order['order']['delivery_country'] = $shippingCountry['countries_name'];
			$order['order']['billing_country'] = $billingCountry['countries_name'];

			if (isset ($ShopInfo['DefaultShippingMethodName'])
                && MagnaDB::gi()->columnExistsInTable('shipping_class',  TABLE_ORDERS)
                && MagnaDB::gi()->columnExistsInTable('shipping_method', TABLE_ORDERS)) {
				$order['order']['shipping_class']  = $ShopInfo['DefaultShippingMethod'];
				$order['order']['shipping_method'] = $ShopInfo['DefaultShippingMethodName'];
			}
	
			if (SHOPSYSTEM != 'oscommerce') {
				$order['order']['customers_status'] = $ShopInfo['CustomerGroup'];
				$order['order']['language'] = $_magnaLanguage;
				
				if (!empty($order['orderInfo']['eBayBuyerUsername']))
					$buyer="\n".'eBay User:   '.$order['orderInfo']['eBayBuyerUsername'];
				else
					$buyer='';
				$order['order']['comments'] = trim(
					sprintf(ML_GENERIC_AUTOMATIC_ORDER_MP_SHORT, $_modules['ebay']['title'])."\n".
					'eBayOrderID: '.$order['orderInfo']['eBayOrderID'].$buyer
				);
			} else {
				# Spalten die osCommerce nicht hat
				unset($order['order']['customers_cid']);
				unset($order['order']['billing_country_iso_code_2']);
				unset($order['order']['delivery_country_iso_code_2']);
			}

            # Gibt es eine Bestellung, zu der man die aktuelle hinzufuegen kann?
            $existingOpenOrder = MagnaDB::gi()->fetchRow('SELECT o.orders_id orders_id, mo.special special, mo.data data '
                .' FROM '.TABLE_ORDERS.' o, '.TABLE_MAGNA_ORDERS.' mo
                WHERE o.customers_id = '.$order['order']['customers_id']
                .' AND o.orders_status = '.$ShopInfo['OrderStatusOpen']
                .' AND o.orders_status <> '.$ShopInfo['OrderStatusClosed']
                .' AND mo.mpID = '.$mpID.' AND o.orders_id = mo.orders_id 
                ORDER BY o.orders_id DESC LIMIT 1');
            if (false != $existingOpenOrder) {
                $ordersId = (int)$existingOpenOrder['orders_id'];
                $magnaOrdersDataArr = unserialize($existingOpenOrder['data']);
                if (!is_array($magnaOrdersDataArr['eBayOrderID'])) {
                    $magnaOrdersDataArr['eBayOrderID'] = array($magnaOrdersDataArr['eBayOrderID'],
                                                            $order['magnaOrders']['eBayOrderID']);
                } else {
                    $magnaOrdersDataArr['eBayOrderID'][] = $order['magnaOrders']['eBayOrderID'];
                }
                $magnaOrdersData = serialize($magnaOrdersDataArr);
                $magnaOrdersSpecial = $existingOpenOrder['special']."\n".$order['orderInfo']['eBayOrderID'];
                # orders_total query
                $existingOrdersTotal = MagnaDB::gi()->fetchArray('SELECT *
                    FROM '.TABLE_ORDERS_TOTAL.' WHERE orders_id = '.$ordersId);
            } else {
                # sonst neue anlegen
			    $MagnaDB->insert(TABLE_ORDERS, $order['order']);
			    $ordersId = $MagnaDB->getLastInsertID();
                $magnaOrdersData = serialize($order['magnaOrders']);
                $magnaOrdersSpecial = $order['orderInfo']['eBayOrderID'];
            }
			/* Bestellung in unserer Tabelle registrieren */
			$MagnaDB->insert(TABLE_MAGNA_ORDERS, array(
				'mpID' => $mpID,
				'orders_id' => $ordersId,
				'orders_status' => $order['order']['orders_status'],
				'data' => $magnaOrdersData,
				'internaldata' => '',
				'special' => $magnaOrdersSpecial,
				'platform' => 'ebay'
			), true);
			// echo 'DELETE FROM '.TABLE_MAGNA_ORDERS.' WHERE orders_id=\''.$ordersId.'\';'."\n\n";
	
			# Statuseintrag fuer Historie vornehmen.
			$order['orderStatus']['orders_id'] = $ordersId;
			$order['orderStatus']['orders_status_id'] = $order['order']['orders_status'];
			
			$order['orderStatus']['comments'] = trim(
				sprintf(ML_GENERIC_AUTOMATIC_ORDER_MP, $_modules['ebay']['title'])."\n".
				'eBayOrderID: '.$order['orderInfo']['eBayOrderID']
			);
	
			$MagnaDB->insert(TABLE_ORDERS_STATUS_HISTORY, $order['orderStatus']);
			// echo 'DELETE FROM '.TABLE_ORDERS_STATUS_HISTORY.' WHERE orders_id=\''.$ordersId.'\';'."\n\n";
	
            # alter subtotal Wert aus orders_total
            $existingValue = 0.0;
            if (false == $existingOrdersTotal) {
			    foreach ($order['orderTotal'] as $key => &$entry) {
				    $entry['orders_id'] = $ordersId;
				    if (defined($entry['title'])) {
					    $entry['title'] = constant($entry['title']);
				    }
				    $entry['text'] = $simplePrice->setPrice($entry['value'])->format();
				    # Das hier ist ot_total, Endsumme.
				    # if not displayPriceWithTax, am Ende kommt noch:
				    # $entry['text'] = $simplePrice->setPrice($entry['value'])->removeTax($tax)->format();
				    # nicht hier, weil wir noch keine Tax haben
				    $MagnaDB->insert(TABLE_ORDERS_TOTAL, $entry);
			    }
			} else {
                # replace statt insert
                foreach ($existingOrdersTotal as $ordersTotalRow) {
                    if (  ('ot_subtotal' == $ordersTotalRow['class'])
                        &&(0.0 == $existingValue)) {
                        # fuer spaeter merken
                        $existingValue = $ordersTotalRow['value'];
                    }
                    if (('ot_subtotal' == $ordersTotalRow['class'])
                        ||('ot_total' == $ordersTotalRow['class'])) {
                        # im 1ten Wurf berechne Versand nur 1 mal, nehme den aelteren Wert
                        # d.h. den neuen gar nicht beruecksichtigen
                        $ordersTotalRow['value'] += $order['orderTotal']['SubTotal']['value'];
                        $ordersTotalRow['text'] = $simplePrice->setPrice($ordersTotalRow['value'])->format();
                        $MagnaDB->insert(TABLE_ORDERS_TOTAL, $ordersTotalRow, true);
                    }
                }
			}
			// echo 'DELETE FROM '.TABLE_ORDERS_TOTAL.' WHERE orders_id=\''.$ordersId.'\';'."\n\n";
	
			$mailOrderSummary = array();
			$taxes = array();
			foreach ($order['products'] as &$prodOrderData) {
				$prodOrderData['products_price'] = $prodOrderData['final_price'] / $prodOrderData['products_quantity'];
				$mailOrderSummary[] = array(
					'quantity' => $prodOrderData['products_quantity'],
					'name' => $prodOrderData['products_name'],
					'price' => $simplePrice->setPrice($prodOrderData['products_price'])->format(),
					'finalprice' => $simplePrice->setPrice($prodOrderData['final_price'])->format(),
				);
	
				if (array_key_exists($prodOrderData['products_id'], $syncBatch)) {
					$syncBatch[$prodOrderData['products_id']]['NewQuantity']['Value'] += (int)$prodOrderData['products_quantity'];
				} else {
					$syncBatch[$prodOrderData['products_id']] = array (
						'SKU' => $prodOrderData['products_id'],
						'NewQuantity' => array (
							'Mode' => 'SUB',
							'Value' => (int)$prodOrderData['products_quantity']
						),
					);
				}
	
				$prodOrderData['orders_id'] = $ordersId;
				$prodOrderData['products_id'] = magnaSKU2pID($prodOrderData['products_id'], true);
				/* Attribute Values ermitteln aus der VariantenSKU von eBay */
				$attrValues = variation_products_model2pOpt($prodOrderData['products_model'], $prodOrderData['products_id']);
	
				if (!MagnaDB::gi()->recordExists(TABLE_PRODUCTS, array('products_id' => (int)$prodOrderData['products_id']))) {
					$prodOrderData['products_id'] = 0;
					$tax = (float)getDBConfigValue($mp.'.mwstfallback', $mpID);
				} else {
					/* Lagerbestand reduzieren */
					if (getDBConfigValue($mp.'.stocksync.frommarketplace', $mpID) != 'no') {
						$MagnaDB->query('
							UPDATE '.TABLE_PRODUCTS.' SET products_quantity = products_quantity - '.(int)$prodOrderData['products_quantity'].' 
							 WHERE products_id='.(int)$prodOrderData['products_id'].'
						');
						/* Varianten-Bestand reduzieren, falls Produkt mit Varianten (gibt es bei osCommerce nicht) */
						if ((!empty($attrValues[0]['options_name']))
						    && (MagnaDB::gi()->columnExistsInTable('attributes_stock',TABLE_PRODUCTS_ATTRIBUTES)) 
						) {
							foreach($attrValues as $attrValue) {
								$MagnaDB->query('
								   UPDATE '.TABLE_PRODUCTS_ATTRIBUTES.' SET attributes_stock = attributes_stock - '.(int)$prodOrderData['products_quantity'].'
								    WHERE products_id='.(int)$prodOrderData['products_id'].' 
								       AND options_id='.(int)$attrValue['options_id'].' 
								       AND options_values_id='.(int)$attrValue['options_values_id'].'
								');
							}
						/* Auch in magnalister_variations */
								$MagnaDB->query('UPDATE '.TABLE_MAGNA_VARIATIONS. '
									SET  variation_quantity = variation_quantity - '.(int)$prodOrderData['products_quantity'].'
									WHERE variation_products_model = \''.$prodOrderData['products_model'].'\'');
						}
					}
					/* Steuersatz und Model holen */
					$row = MagnaDB::gi()->fetchRow('
						SELECT products_tax_class_id, products_model 
						  FROM '.TABLE_PRODUCTS.' 
						 WHERE products_id=\''.(int)$prodOrderData['products_id'].'\'
					');
					if ($row !== false) {
						$tax = SimplePrice::getTaxByClassID((int)$row['products_tax_class_id'], (int)$billingCountry['countries_id']);
						$prodOrderData['products_model'] = $row['products_model'];
					} else {
						$tax = (float)getDBConfigValue($mp.'.mwstfallback', $mpID);
					}
				}
				$prodOrderData['products_tax'] = $tax;
	
				$priceWOTax = $simplePrice->setPrice($prodOrderData['products_price'])->removeTax($tax)->getPrice();
	
				if (!isset($taxes[$tax])) {
					$taxes[$tax] = 0.0;
				}
				$taxes[$tax] += $priceWOTax * (int)$prodOrderData['products_quantity'];
                if (isset($existingValue)) {
                    # ggf Preis der alten Bestellung (ohne Versand) dazunehmen
                    $taxes[$tax] += $simplePrice->setPrice($existingValue)->removeTax($tax)->getPrice();
                }
	
				if (SHOPSYSTEM != 'oscommerce') {
					if($displayPriceWithTax)
						$prodOrderData['allow_tax'] = 1;
					else {
						$prodOrderData['allow_tax'] = 0;
						$prodOrderData['products_price'] = $priceWOTax;
						$prodOrderData['final_price'] = $priceWOTax * (int)$prodOrderData['products_quantity'];
					}
				} else {
					$prodOrderData['products_price'] = $priceWOTax;
					$prodOrderData['final_price'] = $prodOrderData['products_price'];
				}
	
				# Produktdatensatz in Tabelle "orders_products".					
				$MagnaDB->insert(TABLE_ORDERS_PRODUCTS, $prodOrderData);
				$ordersProductsId = $MagnaDB->getLastInsertID();
	
				// orders_products_attributes:
				if ($attrValues) {
				    foreach ($attrValues as $attrValue) {
					$prodOrderAttrData = array(
					    'orders_id' => $prodOrderData['orders_id'],
					    'orders_products_id' => $ordersProductsId,
					    'products_options' => $attrValue['options_name'],
					    'products_options_values' => $attrValue['options_values_name'],
					    'options_values_price' => $attrValue['options_values_price'],
					    'price_prefix' => ''
					);
					if (!empty($attrValue['options_name'])) {
					    $MagnaDB->insert(TABLE_ORDERS_PRODUCTS_ATTRIBUTES, $prodOrderAttrData);
					}
				    }
				}
			}
			// echo 'DELETE FROM '.TABLE_ORDERS_PRODUCTS.' WHERE orders_id=\''.$ordersId.'\';'."\n\n";
	
			/* MwSt Versandkosten */
			if (array_key_exists('Shipping', $order['orderTotal'])) {
				$shippingTax = getDBConfigValue($mp.'.mwst.shipping', $mpID, 19);
				if ($shippingTax > 0) {
					if (!isset($taxes[$shippingTax])) {
						$taxes[$shippingTax] = 0.0;
					}
					$taxes[$shippingTax] += $simplePrice->setPrice($order['orderTotal']['Shipping']['value'])->removeTax($shippingTax)->getPrice();
				}
			}
			
			/* MwSt speichern */
			if (defined('MODULE_ORDER_TOTAL_TAX_STATUS') && (MODULE_ORDER_TOTAL_TAX_STATUS == 'true')) {
				$otc = 60;
				$subtotal_netto = 0.0;
				foreach ($taxes as $key => $sumprice) {
					$taxEntry = array(
						'orders_id' => $ordersId,
						'title' => round($key, 2).'% '.MAGNA_LABEL_ORDERS_TAX,
						'value' => $simplePrice->setPrice($sumprice)->getTaxValue($key),
						'class' => 'ot_tax',
						'sort_order' => $otc
					);
					if (!$displayPriceWithTax) {
						#$taxEntry['title'] = TAX_NO_TAX . round($key, 2).'% '.MAGNA_LABEL_ORDERS_TAX;
						$subtotal_netto += $sumprice;
					}
					$taxEntry['text'] = $simplePrice->setPrice($taxEntry['value'])->format();
					++$otc;
	
                    # Falluntersch. ob neu oder hinzugefuegt
                    if (false == $existingOrdersTotal) {
					    $MagnaDB->insert(TABLE_ORDERS_TOTAL, $taxEntry);
                    } else {
                        foreach ($existingOrdersTotal as $existingRow) {
                            if ('ot_tax' == $existingRow['class']) {
                                $taxEntry['orders_total_id'] = $existingRow['orders_total_id'];
					            $MagnaDB->insert(TABLE_ORDERS_TOTAL, $taxEntry, true);
                                break;
                            }
                        }
                    }
				}
				if (!$displayPriceWithTax) {
					$subtotalNoTaxEntry = array(
						'orders_id' => $ordersId,
						'title' => 'Summe (netto)',
						'text' => $simplePrice->setPrice($subtotal_netto)->format(),
						'value' => $subtotal_netto,
						'class' => 'ot_subtotal_no_tax',
						'sort_order' => '55'
					);
                    # Falluntersch. ob neu oder hinzugefuegt
                    if (false == $existingOrdersTotal) {
					    $MagnaDB->insert(TABLE_ORDERS_TOTAL, $subtotalNoTaxEntry);
					    # und die Eintraege fuer Summe + Versandkosten korrigieren:
					    # erst shipping ohne Steuer, dann ot_subtotal = ot_subtotal_no_tax
					    $shippingWoTax = $simplePrice->setPrice (
						    MagnaDB::gi()->fetchOne('SELECT value FROM '
							    .TABLE_ORDERS_TOTAL.' WHERE orders_id = '.$ordersId
							    .' AND class = \'ot_shipping\' LIMIT 1'
						    ))->removeTax($shippingTax)->getPrice();
					    $MagnaDB->update(TABLE_ORDERS_TOTAL,
						    array('value'=>$shippingWoTax,'text'=>$simplePrice->setPrice($shippingWoTax)->format()),
						    array('orders_id'=>$ordersId,'class'=>'ot_shipping'));
					    $ot_subtotal = 
						    (float)(MagnaDB::gi()->fetchOne('SELECT value FROM '
							    .TABLE_ORDERS_TOTAL.' WHERE orders_id = '.$ordersId
							    .' AND class = \'ot_subtotal_no_tax\' LIMIT 1'
						    ));
					    $MagnaDB->update(TABLE_ORDERS_TOTAL,
						    array('value'=>$ot_subtotal,'text'=>$simplePrice->setPrice($ot_subtotal)->format()),
						    array('orders_id'=>$ordersId,'class'=>'ot_subtotal'));
				    } else {
                        # hinzugefuegt: Steuer & Netto-Summe aendern
                        if ($verbose) echo "Hinzufuegen zur alten Bestellung\n";
                        foreach ($existingOrdersTotal as $existingRow) {
                            if ('ot_tax' == $existingRow['class']) {
                                $taxEntry['orders_total_id'] = $existingRow['orders_total_id'];
					            $MagnaDB->insert(TABLE_ORDERS_TOTAL, $taxEntry, true);
                            }
                            else if ('ot_subtotal_no_tax' == $existingRow['class']) {
                                $subtotalNoTaxEntry['orders_total_id'] = $existingRow['orders_total_id'];
					            $MagnaDB->insert(TABLE_ORDERS_TOTAL, $subtotalNoTaxEntry, true);
                            }
                        }
				    }
				}
			}
	
			if (getDBConfigValue($mp.'.mail.send', $mpID, 'false') == 'true') {
				sendSaleConfirmationMail(
					$mpID,
					$order['customer']['customers_email_address'],
					array(
						'#FIRSTNAME#' => $order['customer']['customers_firstname'],
						'#LASTNAME#' => $order['customer']['customers_lastname'],
						'#EMAIL#' => $order['customer']['customers_email_address'],
						'#PASSWORD#' => $customers_password,
						'#ORDERSUMMARY#' => $mailOrderSummary,
						'#MARKETPLACE#' => $_modules['ebay']['title'],
						'#SHOPURL#' => HTTP_SERVER.DIR_WS_CATALOG,
					)
				);
			}
			unset($customers_password); # nicht dass es versehentlich an weitere Kunden geht
			$lastOrder = $order['order']['date_purchased'];
			if ($verbose) echo "\n### Done.\n\n";
			
			$processedOrders[] = array ('eBayOrderID' => $order['orderInfo']['eBayOrderID'],
						'shopsOrderID' => $ordersId );
		}
		
		if (get_class($MagnaDB) != 'MagnaTestDB') {
			require_once(DIR_MAGNALISTER_CALLBACK.'inventoryUpdate.php');
			magnaInventoryUpdateByOrderImport(array_values($syncBatch), $mpID);
			if ($lastOrder !== '') {
				setDBConfigValue($mp.'.orderimport.lastrun', $mpID, $lastOrder, true);
			}
		}

		/* Acknowledge imported orders */
		$request = array(
			'ACTION' => 'AcknowledgeImportedOrders',
			'SUBSYSTEM' => 'eBay',
			'MARKETPLACEID' => $mpID,
			'DATA' => $processedOrders,
		);
		if (get_class($MagnaDB) != 'MagnaTestDB') {
			try {
				$res = MagnaConnector::gi()->submitRequest($request);
				$processedOrders = array();
			} catch (MagnaException $e) {
				/* don't show these errors. */
				if (MAGNA_CALLBACK_MODE == 'STANDALONE') {
					echo print_m($e->getErrorArray(), 'Error: '.$e->getMessage(), true);
				}
				if ($e->getCode() == MagnaException::TIMEOUT) {
					$e->saveRequest();
					$e->setCriticalStatus(false);
				}
			}
		} else {
			if ($verbose) echo print_m($request);
			$processedOrders = array();
		}
		
	
	}
}
